{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/MITDeepLearning/introtodeeplearning/blob/master/lab3/RL.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jrI6q7RmWQam"
      },
      "source": [
        "<table align=\"center\">\n",
        "  <td align=\"center\"><a target=\"_blank\" href=\"http://introtodeeplearning.com\">\n",
        "        <img src=\"https://i.ibb.co/Jr88sn2/mit.png\" style=\"padding-bottom:5px;\" />\n",
        "      Visit MIT Deep Learning</a></td>\n",
        "  <td align=\"center\"><a target=\"_blank\" href=\"https://colab.research.google.com/github/MITDeepLearning/introtodeeplearning/blob/master/lab3/RL.ipynb\">\n",
        "        <img src=\"https://i.ibb.co/2P3SLwK/colab.png\"  style=\"padding-bottom:5px;\" />Run in Google Colab</a></td>\n",
        "  <td align=\"center\"><a target=\"_blank\" href=\"https://github.com/MITDeepLearning/introtodeeplearning/blob/master/lab3/RL.ipynb\">\n",
        "        <img src=\"https://i.ibb.co/xfJbPmL/github.png\"  height=\"70px\" style=\"padding-bottom:5px;\"  />View Source on GitHub</a></td>\n",
        "</table>\n",
        "\n",
        "# Copyright Information"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wkd375upWYok"
      },
      "outputs": [],
      "source": [
        "# Copyright 2022 MIT 6.S191 Introduction to Deep Learning. All Rights Reserved.\n",
        "# \n",
        "# Licensed under the MIT License. You may not use this file except in compliance\n",
        "# with the License. Use and/or modification of this code outside of 6.S191 must\n",
        "# reference:\n",
        "#\n",
        "# © MIT 6.S191: Introduction to Deep Learning\n",
        "# http://introtodeeplearning.com\n",
        "#"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WoXYKhfZMHiw"
      },
      "source": [
        "# Laboratory 3: Reinforcement Learning\n",
        "\n",
        "Reinforcement learning (RL) is a subset of machine learning which poses learning problems as interactions between agents and environments. It often assumes agents have no prior knowledge of a world, so they must learn to navigate environments by optimizing a reward function. Within an environment, an agent can take certain actions and receive feedback, in the form of positive or negative rewards, with respect to their decision. As such, an agent's feedback loop is somewhat akin to the idea of \"trial and error\", or the manner in which a child might learn to distinguish between \"good\" and \"bad\" actions.\n",
        "\n",
        "In practical terms, our RL agent will interact with the environment by taking an action at each timestep, receiving a corresponding reward, and updating its state according to what it has \"learned\".  \n",
        "\n",
        "![alt text](https://www.kdnuggets.com/images/reinforcement-learning-fig1-700.jpg)\n",
        "\n",
        "While the ultimate goal of reinforcement learning is to teach agents to act in the real, physical world, simulated environments -- like games and simulation engines -- provide a convenient proving ground for developing RL algorithms and agents.\n",
        "\n",
        "In previous labs, we have explored both supervised (with LSTMs, CNNs) and unsupervised / semi-supervised (with VAEs) learning tasks. Reinforcement learning is fundamentally different, in that we are training a deep learning algorithm to govern the actions of our RL agent, that is trying, within its environment, to find the optimal way to achieve a goal. The goal of training an RL agent is to determine the best next step to take to earn the greatest final payoff or return. In this lab, we focus on building a reinforcement learning algorithm to master two different environments with varying complexity. \n",
        "\n",
        "1.   **Cartpole**:   Balance a pole, protruding from a cart, in an upright position by only moving the base left or right. Environment with a low-dimensional observation space.\n",
        "2.   [**Driving in VISTA**](https://www.mit.edu/~amini/pubs/pdf/learning-in-simulation-vista.pdf): Learn a driving control policy for an autonomous vehicle, end-to-end from raw pixel inputs and entirely in the data-driven simulation environment of VISTA. Environment with a high-dimensional observation space -- learning directly from raw pixels.\n",
        "\n",
        "Let's get started! First we'll import TensorFlow, the course package, and some dependencies.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KR9QHuleJ9Bh"
      },
      "outputs": [],
      "source": [
        "# Import Tensorflow 2.0\n",
        "%tensorflow_version 2.x\n",
        "import tensorflow as tf\n",
        "\n",
        "gpus = tf.config.experimental.list_physical_devices('GPU')\n",
        "if gpus:\n",
        "    for gpu in gpus:\n",
        "        tf.config.experimental.set_memory_growth(gpu, True)\n",
        "\n",
        "# Download and import the MIT 6.S191 package\n",
        "!printf \"Installing MIT deep learning package... \"\n",
        "!pip install --upgrade git+https://github.com/MITDeepLearning/introtodeeplearning.git &> /dev/null\n",
        "!echo \"Done\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EvdePP-VyVWp"
      },
      "outputs": [],
      "source": [
        "#Install some dependencies for visualizing the agents\n",
        "!apt-get install -y xvfb python-opengl x11-utils &> /dev/null\n",
        "!pip install gym pyvirtualdisplay scikit-video ffio pyrender &> /dev/null\n",
        "!pip install tensorflow_probability==0.12.0 &> /dev/null\n",
        "import os\n",
        "os.environ['PYOPENGL_PLATFORM'] = 'egl'\n",
        "\n",
        "import numpy as np\n",
        "import matplotlib, cv2\n",
        "import matplotlib.pyplot as plt\n",
        "import base64, io, os, time, gym\n",
        "import IPython, functools\n",
        "import time\n",
        "from tqdm import tqdm\n",
        "import tensorflow_probability as tfp\n",
        "\n",
        "import mitdeeplearning as mdl"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zmrHSiXKTXTY"
      },
      "source": [
        "Before we dive in, let's take a step back and outline our approach, which is generally applicable to reinforcement learning problems in general:\n",
        "\n",
        "1. **Initialize our environment and our agent**: here we will describe the different observations and actions the agent can make in the environemnt.\n",
        "2. **Define our agent's memory**: this will enable the agent to remember its past actions, observations, and rewards.\n",
        "3. **Define a reward function**: describes the reward associated with an action or sequence of actions.\n",
        "4. **Define the learning algorithm**: this will be used to reinforce the agent's good behaviors and discourage bad behaviors.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UT7YL8KBJIIc"
      },
      "source": [
        "# Part 1: Cartpole\n",
        "\n",
        "## 3.1 Define the Cartpole environment and agent\n",
        "\n",
        "### Environment \n",
        "\n",
        "In order to model the environment for the Cartpole task, we'll be using a toolkit developed by OpenAI called [OpenAI Gym](https://gym.openai.com/). It provides several pre-defined environments for training and testing reinforcement learning agents, including those for classic physics control tasks, Atari video games, and robotic simulations. To access the Cartpole environment, we can use `env = gym.make(\"CartPole-v0\")`, which we gained access to when we imported the `gym` package. We can instantiate different [environments](https://gym.openai.com/envs/#classic_control) by passing the enivronment name to the `make` function.\n",
        "\n",
        "One issue we might experience when developing RL algorithms is that many aspects of the learning process are inherently random: initializing game states, changes in the environment, and the agent's actions. As such, it can be helpful to set a initial \"seed\" for the environment to ensure some level of reproducibility. Much like you might use `numpy.random.seed`, we can call the comparable function in gym, `seed`, with our defined environment to ensure the environment's random variables are initialized the same each time."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "quv9SC0iIYFm"
      },
      "outputs": [],
      "source": [
        "### Instantiate the Cartpole environment ###\n",
        "\n",
        "env = gym.make(\"CartPole-v1\")\n",
        "env.seed(1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mhEITUcKK455"
      },
      "source": [
        "In Cartpole, a pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pole starts upright, and the goal is to prevent it from falling over. The system is controlled by applying a force of +1 or -1 to the cart. A reward of +1 is provided for every timestep that the pole remains upright. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center of the track. A visual summary of the cartpole environment is depicted below:\n",
        "\n",
        "<img width=\"400px\" src=\"https://danielpiedrahita.files.wordpress.com/2017/02/cart-pole.png\"></img>\n",
        "\n",
        "Given this setup for the environment and the objective of the game, we can think about: 1) what observations help define the environment's state; 2) what actions the agent can take. \n",
        "\n",
        "First, let's consider the observation space. In this Cartpole environment our observations are:\n",
        "\n",
        "1. Cart position\n",
        "2. Cart velocity\n",
        "3. Pole angle\n",
        "4. Pole rotation rate\n",
        "\n",
        "We can confirm the size of the space by querying the environment's observation space:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UVJaEcbdIX82"
      },
      "outputs": [],
      "source": [
        "n_observations = env.observation_space\n",
        "print(\"Environment has observation space =\", n_observations)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZibGgjrALgPM"
      },
      "source": [
        "Second, we consider the action space. At every time step, the agent can move either right or left. Again we can confirm the size of the action space by querying the environment:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qc9SIPxBIXrm"
      },
      "outputs": [],
      "source": [
        "n_actions = env.action_space.n\n",
        "print(\"Number of possible actions that the agent can choose from =\", n_actions)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pPfHME8aRKkb"
      },
      "source": [
        "### Cartpole agent\n",
        "\n",
        "Now that we have instantiated the environment and understood the dimensionality of the observation and action spaces, we are ready to define our agent. In deep reinforcement learning, a deep neural network defines the agent. This network will take as input an observation of the environment and output the probability of taking each of the possible actions. Since Cartpole is defined by a low-dimensional observation space, a simple feed-forward neural network should work well for our agent. We will define this using the `Sequential` API.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "W-o_XK4oQ4eu"
      },
      "outputs": [],
      "source": [
        "### Define the Cartpole agent ###\n",
        "\n",
        "# Defines a feed-forward neural network\n",
        "def create_cartpole_model():\n",
        "    model = tf.keras.models.Sequential([\n",
        "        # First Dense layer\n",
        "        tf.keras.layers.Dense(units=32, activation='relu'),\n",
        "        \n",
        "        # TODO: Define the last Dense layer, which will provide the network's output.\n",
        "        # Think about the space the agent needs to act in!\n",
        "        # ['''TODO''' Dense layer to output action probabilities]\n",
        "    ])\n",
        "    return model\n",
        "\n",
        "cartpole_model = create_cartpole_model()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d5D5NSIYS2IW"
      },
      "source": [
        "Now that we have defined the core network architecture, we will define an *action function* that executes a forward pass through the network, given a set of observations, and samples from the output. This sampling from the output probabilities will be used to select the next action for the agent. We will also add support so that the `choose_action` function can handle either a single observation or a batch of observations.\n",
        "\n",
        "**Critically, this action function is totally general -- we will use this function for learning control algorithms for Cartpole, but it is applicable to other RL tasks, as well!**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "E_vVZRr8Q4R_"
      },
      "outputs": [],
      "source": [
        "### Define the agent's action function ###\n",
        "\n",
        "# Function that takes observations as input, executes a forward pass through model, \n",
        "#   and outputs a sampled action.\n",
        "# Arguments:\n",
        "#   model: the network that defines our agent\n",
        "#   observation: observation(s) which is/are fed as input to the model\n",
        "#   single: flag as to whether we are handling a single observation or batch of\n",
        "#     observations, provided as an np.array\n",
        "# Returns:\n",
        "#   action: choice of agent action\n",
        "def choose_action(model, observation, single=True):\n",
        "    # add batch dimension to the observation if only a single example was provided\n",
        "    observation = np.expand_dims(observation, axis=0) if single else observation\n",
        "\n",
        "    '''TODO: feed the observations through the model to predict the log probabilities of each possible action.'''\n",
        "    # logits = model.predict('''TODO''')\n",
        "\n",
        "    '''TODO: Choose an action from the categorical distribution defined by the log \n",
        "       probabilities of each possible action.'''\n",
        "    # action = ['''TODO''']\n",
        "\n",
        "    action = action.numpy().flatten()\n",
        "\n",
        "    return action[0] if single else action"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_tR9uAWcTnkr"
      },
      "source": [
        "## 3.2 Define the agent's memory\n",
        "\n",
        "Now that we have instantiated the environment and defined the agent network architecture and action function, we are ready to move on to the next step in our RL workflow:\n",
        "1. **Initialize our environment and our agent**: here we will describe the different observations and actions the agent can make in the environemnt.\n",
        "2. **Define our agent's memory**: this will enable the agent to remember its past actions, observations, and rewards.\n",
        "3. **Define the learning algorithm**: this will be used to reinforce the agent's good behaviors and discourage bad behaviors.\n",
        "\n",
        "In reinforcement learning, training occurs alongside the agent's acting in the environment; an *episode* refers to a sequence of actions that ends in some terminal state, such as the pole falling down or the cart crashing. The agent will need to remember all of its observations and actions, such that once an episode ends, it can learn to \"reinforce\" the good actions and punish the undesirable actions via training. Our first step is to define a simple `Memory` buffer that contains the agent's observations, actions, and received rewards from a given episode. We will also add support to combine a list of `Memory` objects into a single `Memory`. This will be very useful for batching, which will help you accelerate training later on in the lab.\n",
        "\n",
        "**Once again, note the modularity of this memory buffer -- it can and will be applied to other RL tasks as well!**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8MM6JwXVQ4JG"
      },
      "outputs": [],
      "source": [
        "### Agent Memory ###\n",
        "\n",
        "class Memory:\n",
        "    def __init__(self): \n",
        "        self.clear()\n",
        "\n",
        "  # Resets/restarts the memory buffer\n",
        "    def clear(self): \n",
        "        self.observations = []\n",
        "        self.actions = []\n",
        "        self.rewards = []\n",
        "\n",
        "  # Add observations, actions, rewards to memory\n",
        "    def add_to_memory(self, new_observation, new_action, new_reward): \n",
        "        self.observations.append(new_observation)\n",
        "        \n",
        "        '''TODO: update the list of actions with new action'''\n",
        "        # ['''TODO''']\n",
        "\n",
        "        '''TODO: update the list of rewards with new reward'''\n",
        "        # ['''TODO''']\n",
        "\n",
        "    def __len__(self):\n",
        "        return len(self.actions)\n",
        "\n",
        "# Instantiate a single Memory buffer\n",
        "memory = Memory()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "D4YhtPaUVj5m"
      },
      "source": [
        "## 3.3 Reward function\n",
        "\n",
        "We're almost ready to begin the learning algorithm for our agent! The next step is to compute the rewards of our agent as it acts in the environment. Since we (and the agent) is uncertain about if and when the game or task will end (i.e., when the pole will fall), it is useful to emphasize getting rewards **now** rather than later in the future -- this is the idea of discounting. This is a similar concept to discounting money in the case of interest. Recall from lecture, we use reward discount to give more preference at getting rewards now rather than later in the future. The idea of discounting rewards is similar to discounting money in the case of interest.\n",
        "\n",
        "To compute the expected cumulative reward, known as the **return**, at a given timestep in a learning episode, we sum the discounted rewards expected at that time step $t$, within a learning episode, and projecting into the future. We define the return (cumulative reward) at a time step $t$, $R_{t}$ as:\n",
        "\n",
        ">$R_{t}=\\sum_{k=0}^\\infty\\gamma^kr_{t+k}$\n",
        "\n",
        "where  $0 < \\gamma < 1$ is the discount factor and $r_{t}$ is the reward at time step $t$, and the index $k$ increments projection into the future within a single learning episode. Intuitively, you can think of this function as depreciating any rewards received at later time steps, which will force the agent prioritize getting rewards now. Since we can't extend episodes to infinity, in practice the computation will be limited to the number of timesteps in an episode -- after that the reward is assumed to be zero.\n",
        "\n",
        "Take note of the form of this sum -- we'll have to be clever about how we implement this function. Specifically, we'll need to initialize an array of zeros, with length of the number of time steps, and fill it with the real discounted reward values as we loop through the rewards from the episode, which will have been saved in the agents memory. What we ultimately care about is which actions are better relative to other actions taken in that episode -- so, we'll normalize our computed rewards, using the mean and standard deviation of the rewards across the learning episode.\n",
        "\n",
        "We will use this definition of the reward function in both parts of the lab so make sure you have it executed!\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5_Q2OFYtQ32X"
      },
      "outputs": [],
      "source": [
        "### Reward function ###\n",
        "\n",
        "# Helper function that normalizes an np.array x\n",
        "def normalize(x):\n",
        "    x -= np.mean(x)\n",
        "    x /= np.std(x)\n",
        "    return x.astype(np.float32)\n",
        "\n",
        "# Compute normalized, discounted, cumulative rewards (i.e., return)\n",
        "# Arguments:\n",
        "#   rewards: reward at timesteps in episode\n",
        "#   gamma: discounting factor\n",
        "# Returns:\n",
        "#   normalized discounted reward\n",
        "def discount_rewards(rewards, gamma=0.95): \n",
        "    discounted_rewards = np.zeros_like(rewards)\n",
        "    R = 0\n",
        "    for t in reversed(range(0, len(rewards))):\n",
        "        # update the total discounted reward\n",
        "        R = R * gamma + rewards[t]\n",
        "        discounted_rewards[t] = R\n",
        "      \n",
        "    return normalize(discounted_rewards)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QzbY-mjGYcmt"
      },
      "source": [
        "## 3.4 Learning algorithm\n",
        "\n",
        "Now we can start to define the learing algorithm which will be used to reinforce good behaviors of the agent and discourage bad behaviours. In this lab, we will focus on *policy gradient* methods which aim to **maximize** the likelihood of actions that result in large rewards. Equivalently, this means that we want to **minimize** the negative likelihood of these same actions. We achieve this by simply **scaling** the probabilities by their associated rewards -- effectively amplifying the likelihood of actions that resujlt in large rewards.\n",
        "\n",
        "Since the log function is monotonically increasing, this means that minimizing **negative likelihood** is equivalent to minimizing **negative log-likelihood**.  Recall that we can easily compute the negative log-likelihood of a discrete action by evaluting its [softmax cross entropy](https://www.tensorflow.org/api_docs/python/tf/nn/sparse_softmax_cross_entropy_with_logits). Like in supervised learning, we can use stochastic gradient descent methods to achieve the desired minimization. \n",
        "\n",
        "Let's begin by defining the loss function."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fsgZ3IDCY_Zn"
      },
      "outputs": [],
      "source": [
        "### Loss function ###\n",
        "\n",
        "# Arguments:\n",
        "#   logits: network's predictions for actions to take\n",
        "#   actions: the actions the agent took in an episode\n",
        "#   rewards: the rewards the agent received in an episode\n",
        "# Returns:\n",
        "#   loss\n",
        "def compute_loss(logits, actions, rewards): \n",
        "    '''TODO: complete the function call to compute the negative log probabilities'''\n",
        "    # neg_logprob = tf.nn.sparse_softmax_cross_entropy_with_logits(\n",
        "    #    logits='''TODO''', labels='''TODO''')\n",
        "  \n",
        "    '''TODO: scale the negative log probability by the rewards'''\n",
        "    # loss = tf.reduce_mean('''TODO''')\n",
        "    return loss"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Rr5vQ9fqbPpp"
      },
      "source": [
        "Now let's use the loss function to define a training step of our learning algorithm. This is a very generalizable definition which we will use "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_50ada7nbZ7L"
      },
      "outputs": [],
      "source": [
        "### Training step (forward and backpropagation) ###\n",
        "\n",
        "def train_step(model, loss_function, optimizer, observations, actions, discounted_rewards, custom_fwd_fn=None):\n",
        "    with tf.GradientTape() as tape:\n",
        "        # Forward propagate through the agent network\n",
        "        if custom_fwd_fn is not None:\n",
        "            prediction = custom_fwd_fn(observations)\n",
        "        else: \n",
        "            prediction = model(observations)\n",
        "\n",
        "        '''TODO: call the compute_loss function to compute the loss'''\n",
        "        # loss = loss_function('''TODO''', '''TODO''', '''TODO''')\n",
        "\n",
        "    '''TODO: run backpropagation to minimize the loss using the tape.gradient method. \n",
        "             Unlike supervised learning, RL is *extremely* noisy, so you will benefit \n",
        "             from additionally clipping your gradients to avoid falling into \n",
        "             dangerous local minima. After computing your gradients try also clipping\n",
        "             by a global normalizer. Try different clipping values, usually clipping \n",
        "             between 0.5 and 5 provides reasonable results. '''\n",
        "    # grads = tape.gradient('''TODO''', '''TODO''')\n",
        "\n",
        "    # grads, _ = tf.clip_by_global_norm(grads, '''TODO''')\n",
        "    optimizer.apply_gradients(zip(grads, model.trainable_variables))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XsjKXh6BcgjR"
      },
      "source": [
        "## 3.5 Run cartpole!\n",
        "\n",
        "Having had no prior knowledge of the environment, the agent will begin to learn how to balance the pole on the cart based only on the feedback received from the environment! Having defined how our agent can move, how it takes in new observations, and how it updates its state, we'll see how it gradually learns a policy of actions to optimize balancing the pole as long as possible. To do this, we'll track how the rewards evolve as a function of training -- how should the rewards change as training progresses?"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-hZ7E6JOJ9Bn"
      },
      "outputs": [],
      "source": [
        "## Training parameters ##\n",
        "## Re-run this cell to restart training from scratch ##\n",
        "\n",
        "# TODO: Learning rate and optimizer\n",
        "# learning_rate = '''TODO'''\n",
        "\n",
        "# optimizer = '''TODO'''\n",
        "\n",
        "# instantiate cartpole agent\n",
        "cartpole_model = create_cartpole_model()\n",
        "\n",
        "# to track our progress\n",
        "smoothed_reward = mdl.util.LossHistory(smoothing_factor=0.95)\n",
        "plotter = mdl.util.PeriodicPlotter(sec=2, xlabel='Iterations', ylabel='Rewards')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XmOzc2rrcn8Q",
        "scrolled": false
      },
      "outputs": [],
      "source": [
        "## Cartpole training! ##\n",
        "## Note: stoping and restarting this cell will pick up training where you\n",
        "#        left off. To restart training you need to rerun the cell above as \n",
        "#        well (to re-initialize the model and optimizer)\n",
        "\n",
        "if hasattr(tqdm, '_instances'): tqdm._instances.clear() # clear if it exists\n",
        "for i_episode in range(500):\n",
        "\n",
        "    plotter.plot(smoothed_reward.get())\n",
        "    # Restart the environment\n",
        "    observation = env.reset()\n",
        "    memory.clear()\n",
        "\n",
        "    while True:\n",
        "        # using our observation, choose an action and take it in the environment\n",
        "        action = choose_action(cartpole_model, observation)\n",
        "        next_observation, reward, done, info = env.step(action)\n",
        "        # add to memory\n",
        "        memory.add_to_memory(observation, action, reward)\n",
        "\n",
        "        # is the episode over? did you crash or do so well that you're done?\n",
        "        if done:\n",
        "            # determine total reward and keep a record of this\n",
        "            total_reward = sum(memory.rewards)\n",
        "            smoothed_reward.append(total_reward)\n",
        "          \n",
        "            # initiate training - remember we don't know anything about how the \n",
        "            #   agent is doing until it has crashed!\n",
        "            g = train_step(cartpole_model, compute_loss, optimizer, \n",
        "                       observations=np.vstack(memory.observations),\n",
        "                       actions=np.array(memory.actions),\n",
        "                       discounted_rewards = discount_rewards(memory.rewards))\n",
        "          \n",
        "            # reset the memory\n",
        "            memory.clear()\n",
        "            break\n",
        "        # update our observatons\n",
        "        observation = next_observation"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mkcUtGF1VE-K"
      },
      "source": [
        "To get a sense of how our agent did, we can save a video of the trained model working on balancing the pole. Realize that this is a brand new environment that the agent has not seen before!\n",
        "\n",
        "Let's display the saved video to watch how our agent did!\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "PAYBkv6Zbk0J",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "matplotlib.use('Agg') \n",
        "saved_cartpole = mdl.lab3.save_video_of_model(cartpole_model, \"CartPole-v1\")\n",
        "mdl.lab3.play_video(saved_cartpole)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CSbVNDpaVb3_"
      },
      "source": [
        "How does the agent perform? Could you train it for shorter amounts of time and still perform well? Do you think that training longer would help even more? "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Eu6Mqxc720ST"
      },
      "source": [
        "# Part 2: Training Autonomous Driving Policies in VISTA\n",
        "Autonomous control has traditionally be dominated by algorithms that explicitly decompose individual aspects of the control pipeline. For example, in autonomous driving, traditional methods work by first detecting road and lane boundaries, and then using path planning and rule-based methods to derive a control policy. Deep learning offers something very different -- the possibility of optimizing all these steps simultaneously, learning control end-to-end directly from raw sensory inputs.\n",
        "\n",
        "**You will explore the power of deep learning to learn autonomous control policies that are trained *end-to-end, directly from raw sensory data, and entirely within a simulated world*.**\n",
        "\n",
        "We will use the data-driven simulation engine [VISTA](https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8957584&tag=1), which uses techniques in computer vision to synthesize new photorealistic trajectories and driving viewpoints, that are still consistent with the world's appearance and fall within the envelope of a real driving scene. This is a powerful approach -- we can synthesize data that is photorealistic, grounded in the real world, and then use this data for training and testing autonomous vehicle control policies within this simulator.\n",
        "\n",
        "In this part of the lab, you will use reinforcement lerning to build a self-driving agent with a neural network-based controller trained on RGB camera data. We will train the self-driving agent for the task of lane following. Beyond this data modality and control task, VISTA also supports [different data modalities](https://arxiv.org/pdf/2111.12083.pdf) (such as LiDAR data) and [different learning tasks](https://arxiv.org/pdf/2111.12137.pdf) (such as multi-car interactions).\n",
        "<p align=\"center\">\n",
        "<img src=\"https://raw.githubusercontent.com/MITDeepLearning/introtodeeplearning/master/lab3/img/vista_overview.png\" width=\"600\"/>\n",
        "</p>\n",
        "\n",
        "\n",
        "You will put your agent to the test in the VISTA environment, and potentially, on board a full-scale autonomous vehicle! Specifically, as part of the MIT lab competitions, high-performing agents -- evaluated based on the maximum distance they can travel without crashing -- will have the opportunity to be put to the ***real*** test onboard a full-scale autonomous vehicle!!! \n",
        "\n",
        "We start by installing dependencies. This includes installing the VISTA package itself."
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install --upgrade git+https://github.com/vista-simulator/vista-6s191.git"
      ],
      "metadata": {
        "id": "WKWcagMpRLIB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import vista\n",
        "from vista.utils import logging\n",
        "logging.setLevel(logging.ERROR)"
      ],
      "metadata": {
        "id": "ByV6c5GKTgHq"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "70Vpby5VJ9Bp"
      },
      "source": [
        "VISTA provides some documentation which will be very helpful to completing this lab. You can always use the `?vista` command to access the package documentation."
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "### Access documentation for VISTA\n",
        "### Run ?vista.<[name of module or function]>\n",
        "?vista.Display "
      ],
      "metadata": {
        "id": "-RTw0OK4nTYi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.6 Create an environment in VISTA\n",
        "\n",
        "Environments in VISTA are based on and built from human-collected driving *traces*. A trace is the data from a single driving run. In this case we'll be working with RGB camera data, from the viewpoint of the driver looking out at the road: the camera collects this data as the car drives around!\n",
        "\n",
        "We will start by accessing a trace. We use that trace to instantiate an environment within VISTA. This is our `World` and defines the environment we will use for reinforcement learning. The trace itself helps to define a space for the environment; with VISTA, we can use the trace to generate new photorealistic viewpoints anywhere within that space. This provides valuable new training data as well as a robust testing environment.\n",
        "\n",
        "The simulated environment of VISTA will serve as our training ground and testbed for reinforcement learning. We also define an `Agent` -- a car -- that will actually move around in the environmnet, and make and carry out *actions* in this world. Because this is an entirely simulated environment, our car agent will also be simulated!\n",
        "\n"
      ],
      "metadata": {
        "id": "XauFMMZjnYxn"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "scrolled": true,
        "id": "JrTpTBJsJ9Bp"
      },
      "outputs": [],
      "source": [
        "# Download and extract the data for vista (auto-skip if already downloaded)\n",
        "!wget -nc -q --show-progress https://www.dropbox.com/s/62pao4mipyzk3xu/vista_traces.zip\n",
        "print(\"Unzipping data...\")\n",
        "!unzip -o -q vista_traces.zip\n",
        "print(\"Done downloading and unzipping data!\")\n",
        "\n",
        "trace_root = \"./vista_traces\"\n",
        "trace_path = [\n",
        "    \"20210726-154641_lexus_devens_center\", \n",
        "    \"20210726-155941_lexus_devens_center_reverse\", \n",
        "    \"20210726-184624_lexus_devens_center\", \n",
        "    \"20210726-184956_lexus_devens_center_reverse\", \n",
        "]\n",
        "trace_path = [os.path.join(trace_root, p) for p in trace_path]\n",
        "\n",
        "# Create a virtual world with VISTA, the world is defined by a series of data traces\n",
        "world = vista.World(trace_path, trace_config={'road_width': 4})\n",
        "\n",
        "# Create a car in our virtual world. The car will be able to step and take different \n",
        "#   control actions. As the car moves, its sensors will simulate any changes it environment\n",
        "car = world.spawn_agent(\n",
        "    config={\n",
        "        'length': 5.,\n",
        "        'width': 2.,\n",
        "        'wheel_base': 2.78,\n",
        "        'steering_ratio': 14.7,\n",
        "        'lookahead_road': True\n",
        "    })\n",
        "\n",
        "# Create a camera on the car for synthesizing the sensor data that we can use to train with! \n",
        "camera = car.spawn_camera(config={'size': (200, 320)})\n",
        "\n",
        "# Define a rendering display so we can visualize the simulated car camera stream and also \n",
        "#   get see its physical location with respect to the road in its environment. \n",
        "display = vista.Display(world, display_config={\"gui_scale\": 2, \"vis_full_frame\": False})\n",
        "\n",
        "# Define a simple helper function that allows us to reset VISTA and the rendering display\n",
        "def vista_reset():\n",
        "    world.reset()\n",
        "    display.reset()\n",
        "vista_reset()"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "If successful, you should see a blank black screen at this point. Your rendering display has  been initialized."
      ],
      "metadata": {
        "id": "aa3sA9FKndIx"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.7 Our virtual agent: the car\n",
        "\n",
        "Our goal is to learn a control policy for our agent, our (hopefully) autonomous vehicle, end-to-end directly from RGB camera sensory input. As in Cartpole, we need to define how our virtual agent will interact with its environment.\n",
        "\n",
        "### Define agent's action functions\n",
        "In the case of driving, the car agent can act -- taking a step in the VISTA environment -- according to a given control command. This amounts to moving with a desired speed and a desired *curvature*, which reflects the car's turn radius. Curvature has units $\\frac{1}{meter}$. So, if a car is traversing a circle of radius $r$ meters, then it is turning with a curvature $\\frac{1}{r}$. The curvature is therefore correlated with the car's steering wheel angle, which actually controls its turn radius. Let's define the car agent's step function to capture the action of moving with a desired speed and desired curvature."
      ],
      "metadata": {
        "id": "rNzwTTwzngQH"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZjFecj3WJ9Bp"
      },
      "outputs": [],
      "source": [
        "# First we define a step function, to allow our virtual agent to step \n",
        "# with a given control command through the environment \n",
        "# agent can act with a desired curvature (turning radius, like steering angle)\n",
        "# and desired speed. if either is not provided then this step function will \n",
        "# use whatever the human executed at that time in the real data.\n",
        "\n",
        "def vista_step(curvature=None, speed=None):\n",
        "    # Arguments:\n",
        "    #   curvature: curvature to step with\n",
        "    #   speed: speed to step with\n",
        "    if curvature is None: \n",
        "        curvature = car.trace.f_curvature(car.timestamp)\n",
        "    if speed is None: \n",
        "        speed = car.trace.f_speed(car.timestamp)\n",
        "    \n",
        "    car.step_dynamics(action=np.array([curvature, speed]), dt=1/15.)\n",
        "    car.step_sensors()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aRmV3GtkJ9Bp"
      },
      "source": [
        "### Inspect driving trajectories in VISTA\n",
        "\n",
        "Recall that our VISTA environment is based off an initial human-collected driving trace. Also, we defined the agent's step function to defer to what the human executed if it is not provided with a desired speed and curvature with which to move.\n",
        "\n",
        "Thus, we can further inspect our environment by using the step function for the driving agent to move through the environment by following the human path. The stepping and iteration will take about 1 iteration per second. We will then observe the data that comes out to see the agent's traversal of the environment."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rp8G7eirJ9Bp"
      },
      "outputs": [],
      "source": [
        "import shutil, os, subprocess, cv2\n",
        "\n",
        "# Create a simple helper class that will assist us in storing videos of the render\n",
        "class VideoStream():\n",
        "    def __init__(self):\n",
        "        self.tmp = \"./tmp\"\n",
        "        if os.path.exists(self.tmp) and os.path.isdir(self.tmp):\n",
        "            shutil.rmtree(self.tmp)\n",
        "        os.mkdir(self.tmp)\n",
        "    def write(self, image, index):\n",
        "        cv2.imwrite(os.path.join(self.tmp, f\"{index:04}.png\"), image)\n",
        "    def save(self, fname):\n",
        "        cmd = f\"/usr/bin/ffmpeg -f image2 -i {self.tmp}/%04d.png -crf 0 -y {fname}\"\n",
        "        subprocess.call(cmd, shell=True)\n",
        "        "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "scrolled": true,
        "id": "MlC5t0dyJ9Bq"
      },
      "outputs": [],
      "source": [
        "## Render and inspect a human trace ##\n",
        "\n",
        "vista_reset()\n",
        "stream = VideoStream()\n",
        "\n",
        "for i in tqdm(range(100)):\n",
        "    vista_step()\n",
        "    \n",
        "    # Render and save the display\n",
        "    vis_img = display.render()\n",
        "    stream.write(vis_img[:, :, ::-1], index=i)\n",
        "    if car.done: \n",
        "        break\n",
        "\n",
        "print(\"Saving trajectory of human following...\")\n",
        "stream.save(\"human_follow.mp4\")      \n",
        "mdl.lab3.play_video(\"human_follow.mp4\")"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Check out the simulated VISTA environment. What do you notice about the environment, the agent, and the setup of the simulation engine? How could these aspects useful for training models?"
      ],
      "metadata": {
        "id": "SCeRDuqV-bye"
      }
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CvJCRINbJ9Bq"
      },
      "source": [
        "### Define terminal states: crashing! (oh no)\n",
        "\n",
        "Recall from Cartpole, our training episodes ended when the pole toppled, i.e., the agent crashed and failed. Similarly for training vehicle control policies in VISTA, we have to define what a ***crash*** means. We will define a crash as any time the car moves out of its lane or exceeds its maximum rotation. This will define the end of a training episode."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2_6U_VAFJ9Bq"
      },
      "outputs": [],
      "source": [
        "## Define terminal states and crashing conditions ##\n",
        "\n",
        "def check_out_of_lane(car):\n",
        "    distance_from_center = np.abs(car.relative_state.x)\n",
        "    road_width = car.trace.road_width \n",
        "    half_road_width = road_width / 2\n",
        "    return distance_from_center > half_road_width\n",
        "\n",
        "def check_exceed_max_rot(car):\n",
        "    maximal_rotation = np.pi / 10.\n",
        "    current_rotation = np.abs(car.relative_state.yaw)\n",
        "    return current_rotation > maximal_rotation\n",
        "\n",
        "def check_crash(car): \n",
        "    return check_out_of_lane(car) or check_exceed_max_rot(car) or car.done"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YFXUZ8ppJ9Bq"
      },
      "source": [
        "### Quick check: acting with a random control policy\n",
        "\n",
        "At this point, we have (1) an environment; (2) an agent, with a step function. Before we start learning a control policy for our vehicle agent, we start by testing out the behavior of the agent in the virtual world by providing it with a completely random control policy. Naturally we expect that the behavior will not be very robust! Let's take a look."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZIyI5MqwJ9Bq"
      },
      "outputs": [],
      "source": [
        "## Behavior with random control policy ##\n",
        "\n",
        "i = 0\n",
        "num_crashes = 5\n",
        "stream = VideoStream()\n",
        "\n",
        "for _ in range(num_crashes):\n",
        "    vista_reset()\n",
        "    \n",
        "    while not check_crash(car):\n",
        "\n",
        "        # Sample a random curvature (between +/- 1/3), keep speed constant\n",
        "        curvature = np.random.uniform(-1/3, 1/3)\n",
        "\n",
        "        # Step the simulated car with the same action\n",
        "        vista_step(curvature=curvature)\n",
        "\n",
        "        # Render and save the display\n",
        "        vis_img = display.render()\n",
        "        stream.write(vis_img[:, :, ::-1], index=i)\n",
        "        i += 1\n",
        "    \n",
        "    print(f\"Car crashed on step {i}\")\n",
        "    for _ in range(5):\n",
        "        stream.write(vis_img[:, :, ::-1], index=i)\n",
        "        i += 1\n",
        "\n",
        "print(\"Saving trajectory with random policy...\")\n",
        "stream.save(\"random_policy.mp4\")\n",
        "mdl.lab3.play_video(\"random_policy.mp4\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OL02qW5vJ9Br"
      },
      "source": [
        "## 3.8 Preparing to learn a control policy: data preprocessing\n",
        "\n",
        "So, hopefully you saw that the random control policy was, indeed, not very robust. Yikes. Our overall goal in this lab is to build a self-driving agent using a neural network controller trained entirely in the simulator VISTA. This means that the data used to train and test the self-driving agent will be supplied by VISTA. As a step towards this, we will do some data preprocessing to make it easier for the network to learn from these visual data.\n",
        "\n",
        "Previously we rendered the data with a display as a quick check that the environment was working properly. For training the agent, we will directly access the car's observations, extract Regions Of Interest (ROI) from those observations, crop them out, and use these crops as training data for our self-driving agent controller. Observe both the full observation and the extracted ROI."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4UxX6mk5J9Br"
      },
      "outputs": [],
      "source": [
        "from google.colab.patches import cv2_imshow\n",
        "\n",
        "# Directly access the raw sensor observations of the simulated car\n",
        "vista_reset()\n",
        "full_obs = car.observations[camera.name]\n",
        "cv2_imshow(full_obs)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "## ROIs ##\n",
        "\n",
        "# Crop a smaller region of interest (ROI). This is necessary because: \n",
        "#   1. The full observation will have distortions on the edge as the car deviates from the human\n",
        "#   2. A smaller image of the environment will be easier for our model to learn from\n",
        "region_of_interest = camera.camera_param.get_roi()\n",
        "i1, j1, i2, j2 = region_of_interest\n",
        "cropped_obs = full_obs[i1:i2, j1:j2]\n",
        "cv2_imshow(cropped_obs)"
      ],
      "metadata": {
        "id": "KAH-5uxrbkng"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "znxypklaJ9Br"
      },
      "source": [
        "We will group these steps into some helper functions that we can use during training: \n",
        "1. `preprocess`: takes a full observation as input and returns a preprocessed version. This can include whatever preprocessing steps you would like! For example, ROI extraction, cropping, augmentations, and so on. You are welcome to add and modify this function as you seek to optimize your self-driving agent!\n",
        "2. `grab_and_preprocess`: grab the car's current observation (i.e., image view from its perspective), and then call the `preprocess` function on that observation."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7GQY_UwSJ9Br"
      },
      "outputs": [],
      "source": [
        "## Data preprocessing functions ##\n",
        "\n",
        "def preprocess(full_obs):\n",
        "    # Extract ROI\n",
        "    i1, j1, i2, j2 = camera.camera_param.get_roi()\n",
        "    obs = full_obs[i1:i2, j1:j2]\n",
        "    \n",
        "    # Rescale to [0, 1]\n",
        "    obs = obs / 255.\n",
        "    return obs\n",
        "\n",
        "def grab_and_preprocess_obs(car):\n",
        "    full_obs = car.observations[camera.name]\n",
        "    obs = preprocess(full_obs)\n",
        "    return obs"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WAueY4PfJ9Br"
      },
      "source": [
        "## 3.9 Define the self-driving agent and learning algorithm\n",
        "\n",
        "As before, we'll use a neural network to define our agent and output actions that it will take. Fixing the agent's driving speed, we will train this network to predict a curvature -- a continuous value -- that will relate to the car's turn radius. Specifically, define the model to output a prediction of a continuous distribution of curvature, defined by a mean $\\mu$ and standard deviation $\\sigma$. These parameters will define a Normal distribution over curvature.\n",
        "\n",
        "What network architecture do you think would be especially well suited to the task of end-to-end control learning from RGB images? Since our observations are in the form of RGB images, we'll start with a convolutional network. Note that you will be tasked with completing a template CNN architecture for the self-driving car agent -- but you should certainly experiment beyond this template to try to optimize performance!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f-pAQA7zJ9Br"
      },
      "outputs": [],
      "source": [
        "### Define the self-driving agent ###\n",
        "# Note: we start with a template CNN architecture -- experiment away as you \n",
        "#   try to optimize your agent!\n",
        "\n",
        "# Functionally define layers for convenience\n",
        "# All convolutional layers will have ReLu activation\n",
        "act = tf.keras.activations.swish\n",
        "Conv2D = functools.partial(tf.keras.layers.Conv2D, padding='valid', activation=act)\n",
        "Flatten = tf.keras.layers.Flatten\n",
        "Dense = tf.keras.layers.Dense\n",
        "\n",
        "# Defines a CNN for the self-driving agent\n",
        "def create_driving_model():\n",
        "    model = tf.keras.models.Sequential([\n",
        "        # Convolutional layers\n",
        "        # First, 32 5x5 filters and 2x2 stride\n",
        "        Conv2D(filters=32, kernel_size=5, strides=2),\n",
        "\n",
        "        # TODO: define convolutional layers with 48 5x5 filters and 2x2 stride\n",
        "        # Conv2D('''TODO'''),\n",
        "\n",
        "        # TODO: define two convolutional layers with 64 3x3 filters and 2x2 stride\n",
        "        # Conv2D('''TODO'''),\n",
        "\n",
        "        Flatten(),\n",
        "\n",
        "        # Fully connected layer and output\n",
        "        Dense(units=128, activation=act),\n",
        "        \n",
        "        # TODO: define the output dimension of the last Dense layer. \n",
        "        #    Pay attention to the space the agent needs to act in.\n",
        "        #    Remember that this model is outputing a distribution of *continuous* \n",
        "        #    actions, which take a different shape than discrete actions.\n",
        "        #    How many outputs should there be to define a distribution?'''\n",
        "\n",
        "        # Dense('''TODO''')\n",
        "\n",
        "    ])\n",
        "    return model\n",
        "\n",
        "driving_model = create_driving_model()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hlyL0HL1J9Bs"
      },
      "source": [
        "Now we will define the learing algorithm which will be used to reinforce good behaviors of the agent and discourage bad behaviours. As with Cartpole, we will use a *policy gradient* method that aims to **maximize** the likelihood of actions that result in large rewards. However, there are some key differences. In Cartpole, the agent's action space was discrete: it could only move left or right. In driving, the agent's action space is continuous: the control network is outputting a curvature, which is a continuous variable. We will define a probability distribution, defined by a mean and variance, over this continuous action space to define the possible actions the self-driving agent can take.\n",
        "\n",
        "You will define three functions that reflect these changes and form the core of the the learning algorithm:\n",
        "1. `run_driving_model`: takes an input image, and outputs a prediction of a continuous distribution of curvature. This will take the form of a Normal distribuion and will be defined using TensorFlow probability's [`tfp.distributions.Normal`](https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/Normal) function, so the model's prediction will include both a mean and variance. Operates on an instance `driving_model` defined above.\n",
        "2. `compute_driving_loss`: computes the loss for a prediction that is in the form of a continuous Normal distribution. Recall as in Cartpole, computing the loss involves multiplying the predicted log probabilities by the discounted rewards. Similar to `compute_loss` in Cartpole.\n",
        "\n",
        "The `train_step` function to use the loss function to execute a training step will be the same as we used in Cartpole! This will have to be executed abov in order for the driving agent to train properly."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-UWhFhToJ9Bs"
      },
      "outputs": [],
      "source": [
        "## The self-driving learning algorithm ##\n",
        "\n",
        "# hyperparameters\n",
        "max_curvature = 1/8. \n",
        "max_std = 0.1 \n",
        "\n",
        "def run_driving_model(image):\n",
        "    # Arguments:\n",
        "    #   image: an input image\n",
        "    # Returns:\n",
        "    #   pred_dist: predicted distribution of control actions \n",
        "    single_image_input = tf.rank(image) == 3  # missing 4th batch dimension\n",
        "    if single_image_input:\n",
        "        image = tf.expand_dims(image, axis=0)\n",
        "\n",
        "    '''TODO: get the prediction of the model given the current observation.'''    \n",
        "    # distribution = ''' TODO '''\n",
        "\n",
        "    mu, logsigma = tf.split(distribution, 2, axis=1)\n",
        "    mu = max_curvature * tf.tanh(mu) # conversion\n",
        "    sigma = max_std * tf.sigmoid(logsigma) + 0.005 # conversion\n",
        "    \n",
        "    '''TODO: define the predicted distribution of curvature, given the predicted\n",
        "    mean mu and standard deviation sigma. Use a Normal distribution as defined\n",
        "    in TF probability (hint: tfp.distributions)'''\n",
        "    # pred_dist = ''' TODO '''\n",
        "  \n",
        "    return pred_dist\n",
        "\n",
        "\n",
        "def compute_driving_loss(dist, actions, rewards):\n",
        "    # Arguments:\n",
        "    #   logits: network's predictions for actions to take\n",
        "    #   actions: the actions the agent took in an episode\n",
        "    #   rewards: the rewards the agent received in an episode\n",
        "    # Returns:\n",
        "    #   loss\n",
        "    '''TODO: complete the function call to compute the negative log probabilities\n",
        "    of the agent's actions.'''\n",
        "    # neg_logprob = '''TODO'''\n",
        "\n",
        "    '''TODO: scale the negative log probability by the rewards.'''\n",
        "    # loss = tf.reduce_mean('''TODO''')\n",
        "    return loss\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fCCMKLaIJ9Bs"
      },
      "source": [
        "## 3.10 Train the self-driving agent\n",
        "\n",
        "We're now all set up to start training our RL algorithm and agent for autonomous driving!\n",
        "\n",
        "We begin be initializing an opitimizer, environment, a new driving agent, and `Memory` buffer. This will be in the first code block. To restart training completely, you will need to re-run this cell to re-initiailize everything.\n",
        "\n",
        "The second code block is the main training script. Here reinforcement learning episodes will be executed by agents in the VISTA environment. Since the self-driving agent starts out with literally zero knowledge of its environment, it can often take a long time to train and achieve stable behavior -- keep this in mind! For convenience, stopping and restarting the second cell will pick up training where you left off.\n",
        "\n",
        "The training block will execute a policy in the environment until the agent crashes. When the agent crashes, the (state, action, reward) triplet `(s,a,r)` of the agent at the end of the episode will be saved into the `Memory` buffer, and then provided as input to the policy gradient loss function. This information will be used to execute optimization within the training step. Memory will be cleared, and we will then do it all over again!\n",
        "\n",
        "Let's run the code block to train our self-driving agent. We will again visualize the evolution of the total reward as a function of training to get a sense of how the agent is learning. **You should reach a reward of at least 100 to get bare minimum stable behavior.**"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "## Training parameters and initialization ##\n",
        "## Re-run this cell to restart training from scratch ##\n",
        "\n",
        "''' TODO: Learning rate and optimizer '''\n",
        "# learning_rate = '''TODO'''\n",
        "# optimizer = '''TODO'''\n",
        "\n",
        "# instantiate driving agent\n",
        "vista_reset()\n",
        "driving_model = create_driving_model()\n",
        "# NOTE: the variable driving_model will be used in run_driving_model execution\n",
        "\n",
        "# to track our progress\n",
        "smoothed_reward = mdl.util.LossHistory(smoothing_factor=0.9)\n",
        "plotter = mdl.util.PeriodicPlotter(sec=2, xlabel='Iterations', ylabel='Rewards')\n",
        "\n",
        "# instantiate Memory buffer\n",
        "memory = Memory()"
      ],
      "metadata": {
        "id": "uZGn94sJCtBb"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "scrolled": true,
        "id": "G8GhVvZQJ9Bs"
      },
      "outputs": [],
      "source": [
        "## Driving training! Main training block. ##\n",
        "## Note: stopping and restarting this cell will pick up training where you\n",
        "#        left off. To restart training you need to rerun the cell above as \n",
        "#        well (to re-initialize the model and optimizer)\n",
        "\n",
        "max_batch_size = 300\n",
        "max_reward = float('-inf') # keep track of the maximum reward acheived during training\n",
        "if hasattr(tqdm, '_instances'): tqdm._instances.clear() # clear if it exists\n",
        "for i_episode in range(500):\n",
        "\n",
        "    plotter.plot(smoothed_reward.get())\n",
        "    # Restart the environment\n",
        "    vista_reset()\n",
        "    memory.clear()\n",
        "    observation = grab_and_preprocess_obs(car)\n",
        "\n",
        "    while True:\n",
        "        # TODO: using the car's current observation compute the desired \n",
        "        #  action (curvature) distribution by feeding it into our \n",
        "        #  driving model (use the function you already built to do this!) '''\n",
        "        # curvature_dist = '''TODO'''\n",
        "        \n",
        "        # TODO: sample from the action *distribution* to decide how to step\n",
        "        #   the car in the environment. You may want to check the documentation\n",
        "        #   for tfp.distributions.Normal online. Remember that the sampled action\n",
        "        #   should be a single scalar value after this step.\n",
        "        # curvature_action = '''TODO'''\n",
        "        \n",
        "        # Step the simulated car with the same action\n",
        "        vista_step(curvature_action)\n",
        "        observation = grab_and_preprocess_obs(car)\n",
        "               \n",
        "        # TODO: Compute the reward for this iteration. You define \n",
        "        #   the reward function for this policy, start with something \n",
        "        #   simple - for example, give a reward of 1 if the car did not \n",
        "        #   crash and a reward of 0 if it did crash.\n",
        "        #  reward = '''TODO'''\n",
        "        \n",
        "        # add to memory\n",
        "        memory.add_to_memory(observation, curvature_action, reward)\n",
        "        \n",
        "        # is the episode over? did you crash or do so well that you're done?\n",
        "        if reward == 0.0:\n",
        "            # determine total reward and keep a record of this\n",
        "            total_reward = sum(memory.rewards)\n",
        "            smoothed_reward.append(total_reward)\n",
        "            \n",
        "            # execute training step - remember we don't know anything about how the \n",
        "            #   agent is doing until it has crashed! if the training step is too large \n",
        "            #   we need to sample a mini-batch for this step.\n",
        "            batch_size = min(len(memory), max_batch_size)\n",
        "            i = np.random.choice(len(memory), batch_size, replace=False)\n",
        "            train_step(driving_model, compute_driving_loss, optimizer, \n",
        "                               observations=np.array(memory.observations)[i],\n",
        "                               actions=np.array(memory.actions)[i],\n",
        "                               discounted_rewards = discount_rewards(memory.rewards)[i], \n",
        "                               custom_fwd_fn=run_driving_model)            \n",
        "            # reset the memory\n",
        "            memory.clear()\n",
        "            break"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yevBnJCFJ9Bt"
      },
      "source": [
        "## 3.11 Evaluate the self-driving agent\n",
        "\n",
        "Finally we can put our trained self-driving agent to the test! It will execute autonomous control, in VISTA, based on the learned controller. We will evaluate how well it does based on this distance the car travels without crashing. We await the result..."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "scrolled": true,
        "id": "DzeswkSnJ9Bt"
      },
      "outputs": [],
      "source": [
        "## Evaluation block!##\n",
        "\n",
        "i_step = 0\n",
        "num_episodes = 5\n",
        "num_reset = 5\n",
        "stream = VideoStream()\n",
        "for i_episode in range(num_episodes):\n",
        "    \n",
        "    # Restart the environment\n",
        "    vista_reset()\n",
        "    observation = grab_and_preprocess_obs(car)\n",
        "    \n",
        "    print(\"rolling out in env\")\n",
        "    episode_step = 0\n",
        "    while not check_crash(car) and episode_step < 100:\n",
        "        # using our observation, choose an action and take it in the environment\n",
        "        curvature_dist = run_driving_model(observation)\n",
        "        curvature = curvature_dist.mean()[0,0]\n",
        "\n",
        "        # Step the simulated car with the same action\n",
        "        vista_step(curvature)\n",
        "        observation = grab_and_preprocess_obs(car)\n",
        "\n",
        "        vis_img = display.render()\n",
        "        stream.write(vis_img[:, :, ::-1], index=i_step)\n",
        "        i_step += 1\n",
        "        episode_step += 1\n",
        "        \n",
        "    for _ in range(num_reset):\n",
        "        stream.write(np.zeros_like(vis_img), index=i_step)\n",
        "        i_step += 1\n",
        "        \n",
        "print(f\"Average reward: {(i_step - (num_reset*num_episodes)) / num_episodes}\")\n",
        "\n",
        "print(\"Saving trajectory with trained policy...\")\n",
        "stream.save(\"trained_policy.mp4\")\n",
        "mdl.lab3.play_video(\"trained_policy.mp4\")"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Congratulations for making it to this point and for training an autonomous vehicle control policy using deep neural networks and reinforcement learning! Now, with an eye towards the lab competition, think about what you can change -- about the controller model, your data, your learning algorithm... -- to improve performance even further. Below in 3.11 we have some suggestions to get you started. We hope to see your self-driving control policy put to the ***real*** test!"
      ],
      "metadata": {
        "id": "Dq6TZoYvoPyy"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.11 Conclusion and submission information\n",
        "\n",
        "That's it! Congratulations on training two RL agents and putting them to the test! We encourage you to consider the following:\n",
        "\n",
        "* How does each agent perform?\n",
        "* How does the complexity of the self-driving car agent compare to CartPole, and how does it alter the rate at which the agent learns and its performance? \n",
        "* What are some things you could change about the agent or the learning process to potentially improve performance?\n",
        "\n",
        "Try to optimize your **self-driving car** model and algorithm to achieve improved performance.  **MIT students and affiliates will be eligible for prizes during the IAP offering. The prize for this lab includes an opportunity to test your model and algorithm onboard a full-scale autonomous vehicle in the real world.**\n",
        "\n",
        "To get you started, here are some suggested ways to improve your self-driving car model and/or RL algorithm:\n",
        "\n",
        "* different model architectures, for example recurrent models or Transformers with self-attention;\n",
        "* data augmentation and improved pre-processing;\n",
        "* different data modalities from different sensor types. VISTA also supports [LiDAR](https://driving.ca/car-culture/auto-tech/what-is-lidar-and-how-is-it-used-in-cars) and [event-based camera](https://arxiv.org/pdf/1804.01310.pdf) data, with a [new VISTA paper](https://arxiv.org/pdf/2111.12083.pdf) describing this. If you are interested in this, please contact Alexander Amini (amini@mit.edu)!\n",
        "* improved reinforcement learning algorithms, such as [PPO](https://paperswithcode.com/paper/proximal-policy-optimization-algorithms), [TRPO](https://paperswithcode.com/method/trpo), or [A3C](https://paperswithcode.com/method/a3c);\n",
        "* different reward functions for reinforcemnt learning, for example penalizing the car's distance to the lane center rather than just whether or not it crashed;\n",
        "* [Guided Policy Learning (GPL)](https://rll.berkeley.edu/gps/). Not reinforcement learning, but a powerful algorithm to leverage human data to provide additional supervision the learning task.\n",
        "\n",
        "To enter the competition, MIT students and affiliates should upload the following to the course Canvas:\n",
        "\n",
        "* Jupyter notebook with the code you used to generate your results, **with the self-driving car agent training fully executed**;\n",
        "* **saved video of your self-driving agent executing a trajectory in VISTA**;\n",
        "* printout / recording of the **maximum distance traveled by your agent** before crashing;\n",
        "* **text description and/or visual diagram** of the architecture, settings, algorithm, hyperparameters, etc you used to generate your result -- if there are any additional or interesting modifications you made to the template code, please include these in your description;\n",
        "* finally, **separate `.py` script** containing the code for your model, as well as **a function call to load your model and the final trained weights**. This will mean you will have to access and load the weights of your trained model in this script;\n",
        "\n",
        "We will evaluate your entries based on the above components, as well as potential real-time evaluation of top candidates in new VISTA environments with snow / winter traces. The link for these traces is [here](https://www.dropbox.com/s/3wxyvjfquloonqc/vista_traces_snow.zip). You are welcome to download this data and evaluate your models on it as well.\n",
        "\n",
        "Good luck!\n",
        "\n",
        "<p align=\"center\">\n",
        "<img src=\"https://media.giphy.com/media/H7rpSYHRyYgamxQNqw/giphy-downsized-large.gif\" width=\"700\"/>\n",
        "</p>"
      ],
      "metadata": {
        "id": "6c6uO21GoRfw"
      }
    },
    {
      "cell_type": "code",
      "source": [
        ""
      ],
      "metadata": {
        "id": "ac8FNK-x8gNn"
      },
      "execution_count": null,
      "outputs": []
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [
        "WoXYKhfZMHiw",
        "UT7YL8KBJIIc",
        "Eu6Mqxc720ST"
      ],
      "name": "RL.ipynb",
      "provenance": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}